package com.trailwalker.traceability.widget.dialog;

import com.trailwalker.JavaUtils.log.LogUtils;
import com.trailwalker.JavaUtils.string.StringUtils;
import com.trailwalker.javafx.utils.resource.ResourceUtils;
import com.trailwalker.javafx.utils.style.AdaptUtils;
import com.trailwalker.javafx.utils.style.StyleUtils;
import com.trailwalker.javafx.widget.control.imageview.ScaleImageView;
import com.trailwalker.javafx.widget.dialog.CustomDialog;
import com.trailwalker.javafx.widget.dialog.JfxToast;
import com.trailwalker.traceability.util.ImageUtils;
import io.reactivex.functions.Consumer;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author Trailwalker
 * @create 2021-11-11 17:53
 */
public class QrCodeDialog {

    private QrCodeDialogConfig mQrCodeDialogConfig;
    private AdaptUtils mAdaptUtils;
    private AnchorPane mApContent;
    private CustomDialog mCustomDialog;
    private Button mBtnPositive;
    private ScaleImageView mImageView;
    private Image mImage;

    private QrCodeDialog(QrCodeDialogConfig qrCodeDialogConfig) {
        mQrCodeDialogConfig = qrCodeDialogConfig;
        onInit();
    }

    private void onInit() {
        initLoad();
        initView();
        initData();
        initListener();
        onReady();
    }

    public void show() {
        mCustomDialog.show();
    }

    public void dismiss() {
        mCustomDialog.dismiss();
    }

    private void onReady() {
        CustomDialog.CustomDialogBuilder customDialogBuilder = new CustomDialog.CustomDialogBuilder(mQrCodeDialogConfig.primaryStage);
        customDialogBuilder.setPrimaryColor("#026cba");
        String styleSheet = ResourceUtils.getCss(this, "lightTheme.css");
        ArrayList<String> styleSheets = new ArrayList<>();
        styleSheets.add(styleSheet);
        customDialogBuilder.setStylesheets(styleSheets);
        if (mQrCodeDialogConfig.dialogWidth != null) {
            customDialogBuilder.setDialogWidth(mQrCodeDialogConfig.dialogWidth);
        }
        if (mQrCodeDialogConfig.dialogHeight != null) {
            customDialogBuilder.setDialogHeight(mQrCodeDialogConfig.dialogHeight);
        }
        customDialogBuilder.setContentView(mApContent);
        customDialogBuilder.setTitleText("外包装二维码");
        mCustomDialog = customDialogBuilder.build();
    }

    private void initListener() {
        if (mBtnPositive != null) {
            mBtnPositive.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if (event.getButton().equals(MouseButton.PRIMARY)) {
                        saveImage();
                    }
                }
            });

            mBtnPositive.setOnKeyReleased(new EventHandler<KeyEvent>() {
                @Override
                public void handle(KeyEvent event) {
                    if (event.getCode() == KeyCode.ENTER) {
                        if (mBtnPositive.isVisible()) {
                            saveImage();
                        }
                    }
                }
            });
        }
    }

    private void saveImage() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("PNG", "*.png")
        );
        fileChooser.setInitialFileName(getFileName(mQrCodeDialogConfig.imageUrl));
        File file = fileChooser.showSaveDialog(mQrCodeDialogConfig.primaryStage);
        if (file != null) {
            System.out.println(file.getAbsoluteFile());
            if (mImage != null) {
                BufferedImage bufferedImage = SwingFXUtils.fromFXImage(mImage, null);
                try {
                    ImageIO.write(bufferedImage, getFileFormat(mQrCodeDialogConfig.imageUrl), file);
                    JfxToast.makeText(mQrCodeDialogConfig.primaryStage, "保存成功", JfxToast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String getFileName(String imageUrl) {
        String fileNameWithFormat = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        if (fileNameWithFormat.contains("\\")) {
            fileNameWithFormat = imageUrl.substring(imageUrl.lastIndexOf("\\") + 1);
        }
        String fileNameWithoutFormat = fileNameWithFormat.substring(0, fileNameWithFormat.lastIndexOf("."));
        String fileFormat = fileNameWithFormat.substring(fileNameWithFormat.lastIndexOf("."));
        String fileName = fileNameWithoutFormat + "_" + System.currentTimeMillis() + fileFormat;
        return fileName;
    }

    private String getFileFormat(String imageUrl) {
        String fileNameWithFormat = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        if (fileNameWithFormat.contains("\\")) {
            fileNameWithFormat = imageUrl.substring(imageUrl.lastIndexOf("\\") + 1);
        }
        String fileFormat = fileNameWithFormat.substring(fileNameWithFormat.lastIndexOf(".") + 1);
        return fileFormat;
    }

    private void initData() {
        if (mImageView != null) {
            ImageUtils.getImageByUrl(mQrCodeDialogConfig.imageUrl, new Consumer<Image>() {
                @Override
                public void accept(Image image) throws Exception {
                    if (image != null) {
                        mImage = image;
                        mImageView.setImage(mImage);
                        mBtnPositive.setVisible(true);
                    }
                }
            });
        }
    }

    private void initView() {
        mApContent = new AnchorPane();
        StyleUtils.setBackgroundColor(mApContent, "#eeeeee");

        BorderPane bpContent = new BorderPane();
        mApContent.getChildren().add(bpContent);
        mAdaptUtils.setMatchParentAnchorPane(bpContent);

        HBox hbCenter = new HBox();
        bpContent.setCenter(hbCenter);
        hbCenter.setAlignment(Pos.CENTER);

        if (StringUtils.isValid(mQrCodeDialogConfig.imageUrl)) {
            mImageView = new ScaleImageView(300, 300);
            hbCenter.getChildren().add(mImageView);
        }

        HBox hbBottom = new HBox();
        bpContent.setBottom(hbBottom);
        hbBottom.setAlignment(Pos.CENTER);
        mAdaptUtils.setScalePaddingTopAndBottom(hbBottom, 20);

        mBtnPositive = new Button();
        hbBottom.getChildren().add(mBtnPositive);
        mBtnPositive.getStyleClass().add("positive_button");
        mAdaptUtils.setScaleSize(mBtnPositive, 150, 50);
        StyleUtils.setBorderRadius(mBtnPositive, mAdaptUtils.getScale(150), mAdaptUtils.getScale(50), mAdaptUtils.getScale(10));
        StyleUtils.setTextColor(mBtnPositive, "#ffffff");
        mBtnPositive.setText("保存");
        mAdaptUtils.setScaleTextSize(mBtnPositive, 25);
        mBtnPositive.setCursor(Cursor.HAND);
        mBtnPositive.setVisible(false);
    }

    private void initLoad() {
        mAdaptUtils = AdaptUtils.getInstance();
    }

    public static class ConfirmDialogBuilder {
        private QrCodeDialogConfig mQrCodeDialogConfig;

        public ConfirmDialogBuilder(Stage primaryStage) {
            mQrCodeDialogConfig = new QrCodeDialogConfig();
            mQrCodeDialogConfig.primaryStage = primaryStage;
        }

        public ConfirmDialogBuilder setDialogWidth(double dialogWidth) {
            mQrCodeDialogConfig.dialogWidth = dialogWidth;
            return this;
        }

        public ConfirmDialogBuilder setDialogHeight(double dialogHeight) {
            mQrCodeDialogConfig.dialogHeight = dialogHeight;
            return this;
        }

        public ConfirmDialogBuilder setImageUrl(String imageUrl) {
            mQrCodeDialogConfig.imageUrl = imageUrl;
            return this;
        }

        public QrCodeDialog build() {
            return new QrCodeDialog(mQrCodeDialogConfig);
        }

    }

    private static class QrCodeDialogConfig {
        Stage primaryStage;
        Double dialogWidth;
        Double dialogHeight;
        String imageUrl;
    }

}
